package cz.uhk.ppro.controllers;

import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import cz.uhk.ppro.form.Login;
import cz.uhk.ppro.services.PasswordService;
import cz.uhk.ppro.validator.LoginValidator;

@Controller
@SessionAttributes({"login"})
@RequestMapping("/")
public class HomeController {
	
    PasswordService sps;
    LoginValidator loginValidator;
	
	@Autowired
	@Qualifier("passwordService")
	public void setSps(PasswordService sps) {
		this.sps = sps;
	}
	
	
	@Autowired
	public void setLoginValidator(LoginValidator logVal) {
		this.loginValidator = logVal;
	}
		
	@ModelAttribute ("login")
	public Login getLogin() {
		return new Login();
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String showLoginForm(Locale locale, ModelMap model, @ModelAttribute("login") Login login) {
		login = new Login(); 
		login.setGroup("quest");
		model.addAttribute("login", login);	
		return "home";
	}
	
	@RequestMapping(method = RequestMethod.POST)
    public String verify(@ModelAttribute("login")
                            Login login, BindingResult result, ModelMap model, HttpSession session) throws Exception {
		loginValidator.validate(login, result);
        
        if (result.hasErrors()) {
        	return "home";
        	} else {
        		String opr = sps.check(login.getLoginName(), login.getPass());
        		if (opr.compareTo("Skladnik")==0)  { login.setGroup("Skladnik"); session.setAttribute("login", login); return "redirect:/skladnikHome";}
        		if (opr.compareTo("Manager")==0) {login.setGroup("Manager"); session.setAttribute("login", login); return "redirect:/managerHome";}
        		if (opr.compareTo("Admin")==0) {login.setGroup("Admin"); session.setAttribute("login", login); return "redirect:/adminHome";}
        		model.addAttribute("error", "Špatné přihlašovací údaje");	
        		return "home"; 
        	}
    }	
}
